package com.iqiyi.pps.epg.web.timer;

import com.iqiyi.pps.epg.core.model.channel.ChannelBase;
import com.iqiyi.pps.epg.core.model.channel.ChannelConfig;
import com.iqiyi.pps.epg.core.model.control.PlatformControl;
import com.iqiyi.pps.epg.core.model.reservation.ReserveControl;
import com.iqiyi.pps.epg.core.rpc.qipu.QipuService;
import com.iqiyi.pps.epg.core.service.broadcast.BroadcastControlService;
import com.iqiyi.pps.epg.core.service.channel.ChannelService;
import com.iqiyi.pps.epg.core.service.reservation.ReservationService;
import com.iqiyi.pps.epg.core.utils.ApplicationContextUtil;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 预约上下线任务计划，只写奇谱
 * 每3分钟执行
 * 先获取最近6分钟需要处理的上线和下线数据，根据条件设置状态
 */
public class ReservationTrigger {
    private static Logger logger = LoggerFactory.getLogger(ReservationTrigger.class);

    @Autowired
    private ReservationService reservationService;
    @Autowired
    private BroadcastControlService broadcastControlService;
    @Autowired
    private ChannelService channelService;
    @Autowired
    private QipuService qipuService;

    private ConcurrentLinkedQueue<ReserveControl> startQueue;
    private ConcurrentLinkedQueue<ReserveControl> endQueue;

    private SessionFactory sessionFactory;
    private int currentHour = -1;
    private List<ChannelConfig> platformConfigs;

    public void task() {
        // 获取当前时间
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String today = sdf.format(calendar.getTime());
        int endHour = calendar.get(Calendar.HOUR_OF_DAY);
        int endMinute = calendar.get(Calendar.MINUTE);
        calendar.add(Calendar.MINUTE, -6); // 扫描6分钟前的数据
        int startHour = calendar.get(Calendar.HOUR_OF_DAY);
        int startMinute = calendar.get(Calendar.MINUTE);
        String startDay = sdf.format(calendar.getTime());
        String startTime = startDay + " " + startHour + ":" + startMinute + ":00";
        String endTime = today + " " + endHour + ":" + endMinute + ":59";
        logger.info("[ReservationTrigger][task][startTime={}][endTime={}]", startTime, endTime);

        List<ReserveControl> startList = reservationService.getDataByTime(ReservationService.IS_START_TIME, startTime, endTime);
        List<ReserveControl> endList = reservationService.getDataByTime(ReservationService.IS_END_TIME, startTime, endTime);
        logger.info("[ReservationTrigger][task][startSize={}][endSize={}]", startList.size(), endList.size());

        if (startList.size() > 0 || endList.size() > 0) {
            logger.info("[ReservationTrigger][task][startSize={}][endSize={}]", startList.size(), endList.size());
            startQueue = new ConcurrentLinkedQueue<ReserveControl>(startList);
            endQueue = new ConcurrentLinkedQueue<ReserveControl>(endList);

            // 获取配置信息，每小时重新获取次
            if (currentHour != endHour) {
                platformConfigs = channelService.getConfig(ChannelConfig.PLAY_PLATFORM);
                currentHour = endHour;
            }
            sessionFactory = (SessionFactory) ApplicationContextUtil.getBean(SessionFactory.class);
            // WebApplicationContext context = ContextLoader.getCurrentWebApplicationContext();
            // sessionFactory = context.getBean(SessionFactory.class);
            logger.info("[ReservationTrigger][task][thread][start]");
            ExecutorService exec = Executors.newFixedThreadPool(3);
            for (int i = 0; i < 3; i++) {
                exec.execute(new Executor());
            }
        }
    }

    private class Executor implements Runnable {
        @Override
        public void run() {
            while (true) {
                ReserveControl startItem = null;
                ReserveControl endItem = null;
                logger.info("[ReservationTrigger][thread][run]");
                synchronized (startQueue) {
                    if (!startQueue.isEmpty()) {
                        startItem = startQueue.poll();
                    }
                }
                synchronized (endQueue) {
                    if (!endQueue.isEmpty()) {
                        endItem = endQueue.poll();
                    }
                }

                // 无任务退出
                if (startItem == null && endItem == null) {
                    logger.info("[ReservationTrigger][thread][run][break]");
                    break;
                }

                List<PlatformControl> platformControls = new ArrayList();

                try {

                    if (startItem != null) {
                        boolean success = false;
                        ChannelBase channelInfo = channelService.getChannelBase(startItem.getFatherId());
                        if (channelInfo != null) {
                            if (startItem.getType() == ReserveControl.TYPE_BROADCAST) {
                                // 播控设置
                                PlatformControl result = broadcastControlService.getPlatformByUnique(startItem.getFatherId(), startItem.getPlatform());
                                logger.info("[ReservationTrigger][thread][startItem={}]", result);
                                if (result != null) {
                                    sessionFactory.openSession().evict(result);
                                    result.setBlacklist(startItem.getBlacklist());
                                    if (startItem.getOpsStatus() == ReserveControl.OPSSTATUS_ONLINE) {
                                        result.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_ALLOW);
                                    } else {
                                        result.setAvailableStatus(PlatformControl.AVAILABLE_STATUS_DENY);
                                    }
                                    result.setLiveDelayTime(startItem.getDelayTime());
                                    result.setRejectSearch(startItem.getRejectSearch());
                                    result.setRegionRejectSearch( startItem.getRegionRejectSearch());
                                    platformControls.add(result);
                                    for (int i = 0; i < 3; i++) {
                                        if (broadcastControlService.writeQipuBroadcastIgnoreReservation(channelInfo, platformControls, platformConfigs)) {
                                            // if (qipuService.addAccessPlayControlToQipu(channelInfo.getQipuId(), platformControls, platformConfigs, locationConfigs)) {
                                            success = true;
                                            break;
                                        }
                                    }
                                    platformControls.clear();
                                }
                            } else {
                                // 频道改名
                                sessionFactory.openSession().evict(channelInfo);
                                channelInfo.setName(startItem.getBlacklist());
                                for (int i = 0; i < 3; i++) {
                                    if (qipuService.setLiveChannelBaseToQipu(channelInfo.getQipuId(), channelInfo) != -1) {
                                        success = true;
                                        break;
                                    }
                                }
                                // 老奇谱
//                                for (int i = 0; i < 3; i++) {
//                                    if (qipuService.setTvLiveCenterMetadataToQipu(channelInfo.getOldQipuId(), channelInfo) != -1) {
//                                        success = true;
//                                        break;
//                                    }
//                                }
                            }
                        }
                        if (success) {
                            startItem.setStatus(ReserveControl.STATUS_ENABLE_SUCCESS);
                        } else {
                            startItem.setStatus(ReserveControl.STATUS_ENABLE_FAIL);
                        }
                        boolean res = reservationService.save(startItem);
                        logger.info("[ReservationTrigger][thread][save={}][item={}]", res, startItem);
                    }

                    // 预约结束，还原之前的设置
                    if (endItem != null) {
                        boolean success = false;
                        ChannelBase channelInfo = channelService.getChannelBase(endItem.getFatherId());
                        if (channelInfo != null) {
                            if (endItem.getType() == ReserveControl.TYPE_BROADCAST) {
                                // 播控设置
                                PlatformControl result = broadcastControlService.getPlatformByUnique(endItem.getFatherId(), endItem.getPlatform());
                                logger.info("[ReservationTrigger][thread][endItem={}]", result);
                                if (result != null) {
                                    platformControls.add(result);
                                    for (int i = 0; i < 3; i++) {
                                        if (broadcastControlService.writeQipuBroadcastIgnoreReservation(channelInfo, platformControls, platformConfigs)) {
                                            // if (qipuService.addAccessPlayControlToQipu(channelInfo.getQipuId(), platformControls, platformConfigs, locationConfigs)) {
                                            success = true;
                                            break;
                                        }
                                    }
                                    platformControls.clear();
                                }
                            } else {
                                // 频道改名
                                for (int i = 0; i < 3; i++) {
                                    if (qipuService.setLiveChannelBaseToQipu(channelInfo.getQipuId(), channelInfo) != -1) {
                                        success = true;
                                        break;
                                    }
                                }
                                // 老奇谱
//                                for (int i = 0; i < 3; i++) {
//                                    if (qipuService.setTvLiveCenterMetadataToQipu(channelInfo.getOldQipuId(), channelInfo) != -1) {
//                                        success = true;
//                                        break;
//                                    }
//                                }
                            }
                        }
                        if (success) {
                            endItem.setStatus(ReserveControl.STATUS_RENEW_SUCCESS);
                        } else {
                            endItem.setStatus(ReserveControl.STATUS_RENEW_FAIL);
                        }
                        reservationService.save(endItem);
                    }
                } catch (Exception e) {
                    logger.info("[ReservationTrigger][thread][exception=]", e);
                }
            }
        }
    }
}
